package cn.com.surker.system.controller;

import cn.com.surker.common.AbstractController;
import cn.com.surker.common.Code;
import cn.com.surker.common.Constant;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.entity.SysOrgPosition;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.entity.SysPosition;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.IErpOriginService;
import cn.com.surker.system.service.OriginPositionService;
import cn.com.surker.system.service.SysPositionService;
import cn.com.surker.system.service.UserService;
import cn.com.surker.util.ChineseCharacterUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.wechat.WechatOaGroupApi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.RollbackException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* <p>
    * 部门表 前端控制器
    * </p>
*
* @author lucky
* @since 2021-02-24
*/

@RestController
@RequestMapping("/sys_origin")
public class SysOriginController extends AbstractController {

	/**部门业务类**/
	@Autowired
	private IErpOriginService originService;
	@Resource
	private UserService userService;


	@Autowired
	private OriginPositionService originPositionService;

	@Autowired
	private SysPositionService positionService;

	/**
	 * 查询用户当前登录站点的部门
	 * @return
	 */
	@RequestMapping(value = "/query/user/dept", method = RequestMethod.POST)
	public RestResultDto queryUserDept(){
		CacheUser user = getUser();
		Long originId = user.getOriginId();
		if(originId == null){
			return RestResultDto.fail(Code.NO_STATION);
		}
		SysOrigin origin = new SysOrigin();
		origin.setPid(originId);
		List<SysOrigin> list = originService.findAll(origin);
		return RestResultDto.success(list);
	}
	/**
	 * 查询公司下属部门
	 * @return
	 */
	@RequestMapping(value = "/query/org-dept", method = RequestMethod.POST)
	public RestResultDto queryUserDept(Long orgId){
		SysOrigin origin = new SysOrigin();
		origin.setPid(orgId);
		List<SysOrigin> list = originService.findAll(origin);
		return RestResultDto.success(list);
	}

	@RequestMapping(value = "/query/all/origin", method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryAllOrigin(){
		SysOrigin origin = new SysOrigin();
		origin.setType(Constant.SYS_ORIGIN_TYPE_FACTORY);
		List<SysOrigin> list = originService.findAll(origin);
		return RestResultDto.success(list);
	}

	/**
	 * 查询所有部门信息
	 * @return
	 */
	@RequestMapping(value = "/query/all", method = RequestMethod.POST)
	public RestResultDto queryAll(){
		SysOrigin origin = new SysOrigin();
		List<SysOrigin> list = originService.findAll(origin);
		return RestResultDto.success(list);
	}

	/**
	 * 查询部门信息
	 * @return
	 */
	@RequestMapping(value = "/query/user/origin", method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryUserOrigin(SysOrigin origin) {
		try {
			CacheUser user = getUser();
			if (user.getUsername().equals("lucky") || user.getUsername().equals("admin")) {
				List<SysOrigin> list = originService.findAll(origin);
				if (list != null && list.size() > 0)
					return RestResultDto.success(list);
				else
					return RestResultDto.fail("未获取到任何数据");
			}
			List<Map<String, Object>> list = originService.findUserOrigin(origin.getType(), origin.getStatus(), user.getId());
			if (list != null && list.size() > 0)
				return RestResultDto.success(list);
			else
				return RestResultDto.fail("未获取到任何数据");
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultDto.fail("系统异常,加载数据失败");
		}
	}

	/**
	 * 查询所有部门
	 *
	 * @param uid 用户ID
	 * @return
	 */
	@RequestMapping(value = "/query/origin", method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryOrigin(Long uid, Integer type) {
		try {
			List<Map<String, Object>> list = userService.queryRelation(uid, type, null, null);
			if (list == null || list.size() == 0)
				return RestResultDto.fail("未获取到任何数据");
			return RestResultDto.success(list);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultDto.fail("系统异常,加载数据失败");
		}
	}

	/**
	 *  迭代查询部门列表,从大到小（如果没有参数，则查询用户管理的站点)
	 *
	 **/
	@RequestMapping(value = "/relation/list",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryRelationOrigin(Long originId){
		try {
			CacheUser user = getUser();
			if(user == null){
				return RestResultDto.fail("请先登录");
			}
			List<String> roleNameList = user.getRoleNameList();
			if(originId == null){
				if(roleNameList.contains(Constant.SYS_ADMIN)){
					// 如果是管理员，获取全部站点
					originId = 1l;
					List<SysOrigin> origins = originService.relationOriginList(originId);
					return RestResultDto.success(origins);
				}else {
					// 获取用户的绑定的站点
					List<SysOrigin> origins = originService.relationUserOrgList(user.getId());
					return RestResultDto.success(origins);
				}
			}else {
				List<SysOrigin> origins = originService.relationOriginList(originId);
				return RestResultDto.success(origins);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultDto.fail("系统异常,加载数据失败");
		}
	}

	/**
	 * 获取全部站点
	 * @return
	 */
	@RequestMapping(value = "/relation/all/list",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryRelationAllOrigin(){
		try {
			CacheUser user = getUser();
			if(user == null){
				return RestResultDto.fail("请先登录");
			}
			List<SysOrigin> origins = originService.relationOriginList(1l);
			return RestResultDto.success(origins);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultDto.fail("系统异常,加载数据失败");
		}
	}

	/**
	 * 查询登陆用户关联的全部站点
	 * @return
	 */
	@RequestMapping(value = "/user/list",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto queryUserOrigin(){
		try {
			CacheUser user = getUser();
			if(user == null){
				return RestResultDto.fail("请先登录");
			}
			List<SysOrigin> origins = originService.relationUserOrgList(user.getId());
			return RestResultDto.success(origins);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultDto.fail("系统异常,加载数据失败");
		}
	}

	/**
	 * 添加组织机构
	 * @param pid				父级id
	 * @param originName		部门名称
	 * @param fullName			部门全称
	 * @param type				部门类型
	 * @param sortby			排序
	 * @return
	 */
	@RequestMapping(value = "/add",method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto add(Long pid,String originName,String fullName,Integer type,Integer sortby){
		CacheUser user = getUser();
		if(user == null){
			return RestResultDto.fail("请先登录");
		}
		// 验证参数
		if (pid == null){
			return RestResultDto.fail("请选择父级机构");
		}
		if(StringUtils.isBlank(originName)){
			return RestResultDto.fail("请输入机构名称");
		}
		if(type == null){
			return RestResultDto.fail("请选择机构类型");
		}
		if(type == Constant.SYS_ORIGIN_TYPE_FACTORY){
			if(StringUtils.isBlank(fullName)){
				return RestResultDto.fail("工厂类型请输入全称");
			}
		}
		// 验证父级id
		SysOrigin pOrg = originService.getById(pid);
		if(pOrg == null || StateEnum.DISABLED.getCode() == pOrg.getStatus()){
			return RestResultDto.fail("父级机构不存在");
		}
		// 生成公司代码
		String orgCode = ChineseCharacterUtil.convertHanzi2Pinyin(originName, false);
		// 新增数据
		SysOrigin data = new SysOrigin();
		data.setType(type);
		data.setOriginName(originName);
		data.setFullName(fullName);
		data.setPid(pid);
		data.setOrgCode(orgCode);
		data.setSortby(sortby);
		data.setWxOrgId(-1L);
		data.setCreateTime(new Date());
		boolean save = originService.save(data);
		if(save){
			// 添加到企业微信
			JSONObject wechatParam = new JSONObject();
			if (!StringUtils.isNull(pOrg.getWxOrgId()) && pOrg.getWxOrgId() > 0) {
				wechatParam.put("name", data.getOriginName());
				wechatParam.put("parentid", pOrg.getWxOrgId());
				if(sortby != null){
					wechatParam.put("order",sortby);
				}
//				wechatParam.put("id", data.getId());
			} else {
				Long wxOrgId = synGroupWechatOrgId(pOrg.getOriginName(), 2L);
				if (wxOrgId != null) {
					wechatParam.put("name",data.getOriginName());
					wechatParam.put("parentid", wxOrgId);
					if(sortby != null){
						wechatParam.put("order",sortby);
					}
//					wechatParam.put("id",data.getId());
					pOrg.setWxOrgId(wxOrgId);
					originService.updateById(pOrg);
				} else {
					return RestResultDto.success("部门添加成功,企业微信未更新");
				}
			}

			JSONObject obj = WechatOaGroupApi.updateUserOrDepartment(WechatOaGroupApi.corpID, WechatOaGroupApi.corpOriginSecret, WechatOaGroupApi.createOrgUrl, wechatParam);
			if (obj != null) {//更新企业微信ID
				Long id = obj.getLong("id");
				if (StringUtils.isNull(id))
					id = -1L;
				data.setWxOrgId(id);
				originService.updateById(data);
			}

			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}

	/**
	 * 修改组织机构
	 * @param id			旧机构id
	 * @param pid			上级id
	 * @param originName	机构名称
	 * @param fullName		机构全称
	 * @param type			机构类型
	 * @param sortby		排序
	 * @return
	 */
	@RequestMapping(value = "/update/{id}",method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto update(@PathVariable Long id,Long pid,String originName,String fullName,Integer type,Integer sortby){
		CacheUser user = getUser();
		if(user == null){
			return RestResultDto.fail("请先登录");
		}
		if(id == null){
			return RestResultDto.fail("请选择旧机构");
		}
		SysOrigin oldData = originService.getById(id);

		if(oldData == null || StateEnum.DISABLED.getCode() == oldData.getStatus()){
			return RestResultDto.fail("旧机构不存在");
		}
		if(pid != null){
			// 验证父级机构
			SysOrigin pOrg = originService.getById(pid);
			if(pOrg == null || StateEnum.DISABLED.getCode() == pOrg.getStatus()){
				return RestResultDto.fail("父级机构不存在");
			}
			oldData.setPid(pid);
		}
		if(StringUtils.isNotBlank(originName)){
			oldData.setOriginName(originName);
		}
		if(StringUtils.isNotBlank(fullName)){
			oldData.setFullName(fullName);
		}
		if(type != null){
			oldData.setType(type);
		}
		if(sortby != null){
			oldData.setSortby(sortby);
		}
		// 生成公司代码
		String orgCode = ChineseCharacterUtil.convertHanzi2Pinyin(originName, false);
		oldData.setOrgCode(orgCode);
		boolean b = originService.updateById(oldData);
		if(b){
			JSONObject wechatParam = new JSONObject();
			wechatParam.put("name",originName);
			if(sortby != null){
				wechatParam.put("order",sortby);
			}
			wechatParam.put("id", oldData.getWxOrgId());
			WechatOaGroupApi.updateUserOrDepartment(WechatOaGroupApi.corpID,WechatOaGroupApi.corpOriginSecret,WechatOaGroupApi.updateOrgUrl,wechatParam);
			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}


	/**
	 * 删除组织机构
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete",method = RequestMethod.DELETE)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto delete(Long id){
		CacheUser user = getUser();
		if(user == null){
			return RestResultDto.fail("请先登录");
		}
		if(id == null){
			return RestResultDto.fail("请选择机构");
		}
		// 判断是否有用户
		List<SysUser> users = originService.relationOriginUserList(id, null, null, StateEnum.ENABLED.getCode());
		if(user != null && !users.isEmpty()){
			return RestResultDto.fail("该机构或其下级机构有用户");
		}
		// 获取待删除的机构和所有的子集机构
		List<SysOrigin> sysOrigins = originService.relationOriginList(id);
		List<Long> ids = RelationDelete(sysOrigins);
		// 更新到企业微信
		for(Long did : ids){
			JSONObject wechatParam = new JSONObject();
			wechatParam.put("id",did);
			WechatOaGroupApi.deleteUserOrDepartment(WechatOaGroupApi.corpID,WechatOaGroupApi.corpOriginSecret,WechatOaGroupApi.deleteOrgUrl,wechatParam);
		}
		return RestResultDto.success();
	}

	// 将岗位设置到组织机构
	@RequestMapping(value = "/bind/position",method = RequestMethod.PUT)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto bindPosition(Long orgId,Long posId,Long parentPosId,Integer isBoss){
		if(orgId == null || posId == null || parentPosId == null || isBoss == null){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		if(isBoss != 0 && isBoss != 1){
			return RestResultDto.fail(Code.PARAM_ERROR.getCode(),"是否boss参数非法");
		}
		// 查询组织机构是否存在
		SysOrigin org = originService.getById(orgId);
		if(org == null){
			return RestResultDto.fail(Code.PARAM_ERROR.getCode(),"组织机构不存在");
		}
		// 查询岗位是否存在
		SysPosition position = positionService.getById(posId);
		if(position == null){
			return RestResultDto.fail(Code.PARAM_ERROR.getCode(),"岗位不存在");
		}
		// 查询上级岗位是否存在
		SysPosition pPos = positionService.getById(parentPosId);
		if(pPos == null){
			return RestResultDto.fail(Code.PARAM_ERROR.getCode(),"上级岗位不存在");
		}
		// 查询是否存在数据
		SysOrgPosition oldData = originPositionService.queryOrgPos(orgId,posId);
		if(oldData != null){
			// 之前存在数据，更新上级岗位
			oldData.setParentPid(parentPosId);
			oldData.setCreateTime(new Date());
			oldData.setIsBoss(isBoss);
			Integer u = originPositionService.updateOrgPosById(oldData);
			if(u > 0){
				return RestResultDto.success();
			}else {
				return RestResultDto.fail();
			}
		} else {
			// 之前不存在，直接新增
			SysOrgPosition orgPosition = new SysOrgPosition();
			orgPosition.setOrgId(orgId);
			orgPosition.setPid(posId);
			orgPosition.setParentPid(parentPosId);
			orgPosition.setIsBoss(isBoss);
			orgPosition.setStatus(StateEnum.ENABLED.getCode());
			Integer r = originPositionService.saveInitOrgPos(orgPosition);
			if(r > 0){
				return RestResultDto.success();
			}else {
				return RestResultDto.fail();
			}
		}
	}

	/**
	 * 删除 机构下的岗位
	 * @param orgPosId
	 * @return
	 */
	@RequestMapping(value = "/del/position",method = RequestMethod.DELETE)
	@ResponseBody
	@Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
	public RestResultDto delPosition(Long orgPosId){
		if(orgPosId == null){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		// 先查询该岗位
		SysOrgPosition orgPosition = originPositionService.queryById(orgPosId);
		if(orgPosition == null){
			return RestResultDto.fail("该绑定关系不存在");
		}
		// 验证该机构的岗位下是否存在用户
		List<SysUser> users = userService.queryUsersByOrgPos(orgPosition.getOrgId(), orgPosition.getPid(),null);
		if(users != null && !users.isEmpty()){
			// 存在用户
			return RestResultDto.fail("该岗位下存在绑定用户，不允许删除");
		}
		Integer delete = originPositionService.deleteOrgPos(orgPosId);
		if(delete > 0){
			return RestResultDto.success();
		}else {
			return RestResultDto.fail();
		}
	}

	// 查询组织机构下的全部岗位
	@RequestMapping(value = "/query/position",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto selectPosition(Long orgId){
		if(orgId == null){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		List<Map<String,Object>> orgPositions = originPositionService.queryPositionByOrg(orgId);
		return RestResultDto.success(orgPositions);
	}

	// 根据简称查全称
	@RequestMapping(value = "/query/fullName",method = RequestMethod.POST)
	@ResponseBody
	public RestResultDto selectPosition(String shortName){
		if(StringUtils.isBlank(shortName)){
			return RestResultDto.fail(Code.PARAM_EMPTY);
		}
		SysOrigin sysOrigin = new SysOrigin();
		sysOrigin.setOriginName(shortName);
		List<SysOrigin> all = originService.findAll(sysOrigin);
		if(all == null || all.isEmpty()){
			return RestResultDto.fail(Code.NO_DATA);
		}
		SysOrigin origin = all.get(0);
		String fullName = origin.getFullName();
		return RestResultDto.success("",fullName);
	}

	/**
	 * 迭代删除部门包括子部门的数据,返回删除的全部子集id
	 * @param origins
	 * @return
	 */
	private List<Long> RelationDelete(List<SysOrigin> origins){
		List<Long> ids = new ArrayList<>();
		if(origins != null && !origins.isEmpty()){
			for(SysOrigin origin : origins){
				// 删除本身
				Long id = origin.getId();
				UpdateWrapper<SysOrigin> uwi = new UpdateWrapper<>();
				uwi.eq("id",id);
				uwi.set("status",StateEnum.DISABLED.getCode());
				originService.update(uwi);
				if (!StringUtils.isNull(origin.getWxOrgId()) && origin.getWxOrgId() > -1)
					ids.add(origin.getWxOrgId());
				// 删除子级机构
				List<SysOrigin> children = origin.getChildren();
				List<Long> cids = RelationDelete(children);
				if(cids != null && !cids.isEmpty()){
					ids.addAll(cids);
				}
			}
		}
		return ids;
	}


	private Long synGroupWechatOrgId(String name, Long wxOrgId) {
		if (StringUtils.isAllParamNull(name, wxOrgId))
			return null;
		JSONObject json = new JSONObject();
		json.put("id", wxOrgId);

		JSONObject jo = WechatOaGroupApi.updateUserOrDepartment(WechatOaGroupApi.corpID,WechatOaGroupApi.corpOriginSecret,WechatOaGroupApi.synOrgUrl, json);
		if (jo != null && jo.getInteger("errcode") == 0) {
			JSONArray ja = jo.getJSONArray("department");
			if (ja != null && ja.size() > 0) {
				for (int i = 0; i < ja.size(); i++) {
					JSONObject jo1 = ja.getJSONObject(i);
					String wxName = jo1.getString("name");
					Long parentid = jo1.getLong("parentid");
					if (name.equals(wxName) && parentid.intValue() == wxOrgId.intValue())
						return jo1.getLong("id");
				}
			}
		}

		return null;
	}

}



